package com.cmos.um.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.cmos.um.beans.CtiMessage;
import com.cmos.um.beans.CtiMessageExtends;
import com.cmos.um.iservice.ICtiMessageSV;
import com.cmos.um.iservice.ITaskMemSV;
import com.cmos.um.utils.RetMap;
import com.cmos.um.utils.WSContent;
import com.cmos.um.utils.WSRtnJsonCtx;
import com.cmos.um.utils.http.RestClientHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskMemSVImpl implements ITaskMemSV {
    @Autowired
    private ICtiMessageSV ctiMessageservice;
    @Autowired
    private RestClientHttpRequest clien;

    private final static Logger logger = LoggerFactory.getLogger(TaskMemSVImpl.class);


    /**
     * 【操作】获取任务简要信息列表
     *
     * @param params 参数集MAP（含params参数——此参数在输入函数时为Json字符串）
     * @return Map<String,Object> 返回的数据（MAP形式）
     */
    @Override
    public Map<String, Object> briefList(JSONObject params) {

        //发送给cti的数据对象
        JSONObject toCC = new JSONObject();
        List<CtiMessage> ctiMessage = ctiMessageservice.queryAll();
        //处理收到的数据提取其中的params中的map
        JSONObject P_params = params.getJSONObject("params");

        if (ctiMessage.isEmpty()) {
            return new RetMap(logger, "尚未建设（和注册）任何的CC平台");
        }
        String ctiId = null; // CC平台编号（名称）
        String ctiIp = null; // CTI服务器的IP地址
        String ctiPort = null; // CTI服务器的端口号

        List<Map<String, Object>> returnBriefListBeans = new ArrayList<Map<String, Object>>();

        for (CtiMessage ctiMessageInfo : ctiMessage) {
            ctiId = ctiMessageInfo.getCtiId();
            ctiIp = ctiMessageInfo.getCtiIp();
            ctiPort = ctiMessageInfo.getCtiPort();

            try {
                String type = P_params.getString("type");
                if ("1".equals(type)) {
                    toCC.put("serviceType", "10");
                } else {
                    toCC.put("serviceType", "11");
                }
                toCC.put("vccId", P_params.getString("vccId"));
                toCC.put("dbName", "memcache1");
                toCC.put("tableName", "OUT");
//                JSONObject toCCFinal = RetMap.toCINCCJSONObject(toCC, "listSomeKeyValue", "3");
                //想cti查询改vccid下的所有外呼任务简要信息

                Map<String, Object> retTaskOutput = new HashMap<>();//接收查到的任务信息

//                retTaskOutput = (Map<String, Object>)WSRequest.send(ctiIp + ((ctiPort != null) ? (":" + ctiPort): ""), "/jsonVcc", toCCFinal);
                WSRtnJsonCtx wsRtnJsonCtx = clien.doPost(WSContent.memUrl, ctiIp, "listSomeKeyValue", "3", toCC);
//                System.out.println(wsRtnJsonCtx.getOutputObj());
                List<Map<String, Object>> retTaskOutputArray = (List<Map<String, Object>>) wsRtnJsonCtx.getOutputObj().get("contextArray");

                for (Map<String, Object> retTaskOutputArrayInfo : retTaskOutputArray) {
                    if (retTaskOutputArrayInfo.containsKey("STTM")) {
                        Map<String, Object> returnBriefListBean = new HashMap<>();
                        returnBriefListBean.put("taskId", retTaskOutputArrayInfo.get("taskId"));
                        returnBriefListBean.put("taskName", retTaskOutputArrayInfo.get("taskName"));
                        returnBriefListBean.put("sttm", retTaskOutputArrayInfo.get("STTM"));
                        returnBriefListBean.put("sype", retTaskOutputArrayInfo.get("TYPE"));
                        returnBriefListBean.put("sped", retTaskOutputArrayInfo.get("SPED"));
                        returnBriefListBean.put("rate", retTaskOutputArrayInfo.get("RATE"));
                        returnBriefListBean.put("prgs", retTaskOutputArrayInfo.get("PRGS"));
                        returnBriefListBean.put("cont", retTaskOutputArrayInfo.get("CONT"));
                        returnBriefListBean.put("cnrt", retTaskOutputArrayInfo.get("CNRT"));
                        returnBriefListBean.put("redy", retTaskOutputArrayInfo.get("REDY"));
                        returnBriefListBean.put("rdsc", retTaskOutputArrayInfo.get("RDSC"));
                        returnBriefListBean.put("serv", retTaskOutputArrayInfo.get("SERV"));
                        returnBriefListBean.put("svsc", retTaskOutputArrayInfo.get("SVSC"));

                        returnBriefListBeans.add(returnBriefListBean);
                    }
                }
            } catch (Exception e) {
                logger.error("在CTI平台查询vccid=" + ctiId + "失败，" + e.getMessage() + "，请求参数为｛" + toCC.toJSONString() + "｝，原始请求消息为｛" + params.toString() + "｝");
                continue;
            }
        }
        return new RetMap(returnBriefListBeans);
    }


    /**
     * 【操作】获取任务详情信息
     *
     * @param params 参数集MAP（含params参数——此参数在输入函数时为Json字符串）
     * @return Map<String,Object> 返回的数据（MAP形式）
     */
    @Override
    public Map<String, Object> taskDetail(JSONObject params) {

        //发送给cti的数据对象
        JSONObject toCC = new JSONObject();

        JSONObject P_params = params.getJSONObject("params");
        String taskId = P_params.getString("taskId");// CTI服务器中的任务号

        //String campaignId = taskId.substring(14, taskId.length());// 统一调度处的任务id

        CtiMessageExtends ctiMessageExtends = ctiMessageservice.queryCtimessageBytaskId(taskId);
        if (ctiMessageExtends == null) {
            return new RetMap("0", "没有找到此任务号对应的cti");
        }
        String ctiId = ctiMessageExtends.getCtiId();
        String ctiIp = ctiMessageExtends.getCtiIp();
        //处理收到的数据提取其中的params中的map


        Map<String, Object> returnDetailBean = new HashMap<>();
        //返回的对象
        try {
            toCC.put("taskId", taskId);
            toCC.put("dbName", "memcache1");
            toCC.put("tableName", "OUT");
            toCC.put("serviceId", ctiMessageExtends.getTaskXfId());
            JSONObject toCCFinal = RetMap.toCINCCJSONObject(toCC, "listSomeKeyValue", "3");
            //想cti查询改vccid下的所有外呼任务简要信息

            Map<String, Object> retTaskOutput = null;//接收查到的任务信息

//            retTaskOutput = (Map<String, Object>) WSRequest.send(ctiIp + ((ctiPort != null) ? (":" + ctiPort): ""), "/jsonVcc", toCCFinal);
            WSRtnJsonCtx wsRtnJsonCtx = clien.doPost(WSContent.memUrl, ctiIp, "listSomeKeyValue", "3", toCC);
            if ("0".equals(wsRtnJsonCtx.getRescode()) && !wsRtnJsonCtx.getOutputObj().isEmpty()) {
                Map<String, Object> returnDetailTaskOutput = ((List<Map<String, Object>>) (wsRtnJsonCtx.getOutputObj().get("contextArray"))).get(0);

                returnDetailBean.put("taskInfo", replace(returnDetailTaskOutput.get("TASK_INFO").toString()));
                returnDetailBean.put("taskProgress", replace(returnDetailTaskOutput.get("TASK_PROGRESS").toString()));
                returnDetailBean.put("taskSpeed", replace(returnDetailTaskOutput.get("TASK_SPEED").toString()));
                returnDetailBean.put("taskAgent", replace(returnDetailTaskOutput.get("TASK_AGENT").toString()));
                returnDetailBean.put("taskRecord", replace(returnDetailTaskOutput.get("TASK_RECORD").toString()));
                returnDetailBean.put("taskDebug", replace(returnDetailTaskOutput.get("TASK_DEBUG").toString()));
                returnDetailBean.put("taskStatistics", replace(returnDetailTaskOutput.get("TASK_STATISTICS").toString()));
            } else if ("0".equals(wsRtnJsonCtx.getRescode()) && wsRtnJsonCtx.getOutputObj().isEmpty()) {
                return new RetMap("0", "没有查询到此任务相关信息！");
            } else {
                logger.error("调用cti接口异常，返回的信息为：" + wsRtnJsonCtx.getResJsonObj());
                return new RetMap("0", "调用cti接口异常");
            }

        } catch (Exception e) {
            logger.error("在CTI平台查询ctiId=" + ctiId + "请求taskId = " + taskId + "的详细任务信息失败，" + e.getMessage() + "，请求参数为｛" + toCC.toJSONString() + "｝，原始请求消息为｛" + params.toString() + "｝");
            return new RetMap("0", "服务器捕获到异常");
        }
        return new RetMap(returnDetailBean);
    }


    private String replace(String sourceString) {
        String replaceString = sourceString;
        replaceString = replaceString.replace("$", "\"");
        return replaceString;
    }


}
